﻿﻿using System.Windows;
using vlcplay.ViewModels;
using VideoClient;
using System.Windows.Controls;
using MahApps.Metro.Controls; // 引用你的 XhVideoClient
using System.Text.Json;

namespace vlcplay
{
    public partial class LoginWindow : MetroWindow
    {
        private readonly XhVideoClient _videoClient;

        public string UserName => ((LoginViewModel)DataContext).UserName;
        public string Password => ((LoginViewModel)DataContext).Password;
        public bool RememberMe => ((LoginViewModel)DataContext).RememberMe;
        public string AccessToken => _videoClient.AccessToken;

        public LoginWindow(XhVideoClient videoClient)
        {
            InitializeComponent();
            _videoClient = videoClient;
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
            {
                MessageBox.Show("请输入用户名和密码");
                return;
            }

            // _videoClient.Login now handles internal 'code' checking and token parsing.
            // 'success' indicates overall login success (including business logic code == 0 and token presence).
            // 'responseMessage' contains the server's raw response, useful for error details.
            var responseMessage = _videoClient.Login(UserName, Password, out bool success);

            if (!success)
            {
                string displayMessage = "登录失败，请检查用户名、密码或网络连接。"; // Default message
                if (!string.IsNullOrEmpty(responseMessage))
                {
                    try
                    {
                        // Attempt to parse the message for a more specific error from the server
                        using var doc = JsonDocument.Parse(responseMessage);
                        var root = doc.RootElement;
                        if (root.TryGetProperty("msg", out var msgElement) && msgElement.ValueKind == JsonValueKind.String)
                        {
                            displayMessage = msgElement.GetString() ?? displayMessage;
                        }
                        else if (root.TryGetProperty("message", out var messageElement) && messageElement.ValueKind == JsonValueKind.String) // Common alternative
                        {
                             displayMessage = messageElement.GetString() ?? displayMessage;
                        }
                        // If it's not JSON but a plain string, use it if it's not empty
                        else if (!responseMessage.TrimStart().StartsWith("{") && !string.IsNullOrWhiteSpace(responseMessage))
                        {
                            displayMessage = responseMessage;
                        }
                    }
                    catch (JsonException)
                    {
                        // If parsing fails, and responseMessage is not empty, use it directly.
                        if (!string.IsNullOrWhiteSpace(responseMessage))
                        {
                            displayMessage = responseMessage;
                        }
                    }
                }
                MessageBox.Show(displayMessage);
                return;
            }

            // Login was successful as determined by XhVideoClient
            DialogResult = true;
        }

        private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (DataContext is LoginViewModel vm && sender is PasswordBox pb)
            {
                vm.Password = pb.Password;
            }
        }
    }
}
